//
//  NSCustomAlertView.m
//  MacDevTest
//
//  Created by lbxia on 2022/9/2.
//  Copyright © 2022 com.lbx. All rights reserved.
//

#import "NSCustomAlertView.h"
#import "NSCustomTransparentView.h"


@interface NSCustomAlertView()
@property (nonatomic, strong) NSImageView *imageView;
@property (nonatomic, strong) NSTextField *titleField;
@property (nonatomic, strong) NSTextField *contentField;

@property (nonatomic, strong) NSButton *cancelBtn;
@property (nonatomic, strong) NSButton *sureBtn;

//存储透明背景
@property (nonatomic, strong) NSView *windowTransparentckView;


@property (nonatomic, copy) void (^cancel)(void);
@property (nonatomic, copy) void (^sure)(void);

//自定义按钮标题，数量，返回等，默认是按钮是蓝色背景的，其他白色背景，灰度边框
@property (nonatomic, strong) NSArray<NSString*> *buttonTitles;
@property (nonatomic, assign) NSInteger defaultIdx;
@property (nonatomic, copy) void (^onAction)(NSInteger idx,NSString *title);

@end

@implementation NSCustomAlertView

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}

- (BOOL)isFlipped
{
    return YES;
}

- (id)init {
    if (self = [super init]) {
        
//        [self setUI];
    }
    return self;
}

- (void)setUI {
    
    
    //左侧图标
    self.imageView = [[NSImageView alloc]init];
    [self addSubview:self.imageView];
    _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    [_imageView.leftAnchor constraintEqualToAnchor:self.leftAnchor constant:30].active = YES;
    [_imageView.topAnchor constraintEqualToAnchor:self.topAnchor constant:48].active = YES;
    [_imageView.widthAnchor constraintEqualToConstant:24].active = YES;
    [_imageView.heightAnchor constraintEqualToConstant:24].active = YES;
    

    //标题
    self.titleField = [[NSTextField alloc]init];
    _titleField.editable = NO;
    _titleField.bordered = NO;
    _titleField.selectable  = NO;
    _titleField.backgroundColor = NSColor.whiteColor;
    _titleField.font = [NSFont systemFontOfSize:16];
    _titleField.textColor = [NSColor colorWithRed:38/255. green:42/255. blue:48/255. alpha:1];
    _titleField.maximumNumberOfLines = 0;

    [self addSubview:_titleField];
    _titleField.translatesAutoresizingMaskIntoConstraints = NO;
    [_titleField.leftAnchor constraintEqualToAnchor:self.imageView.rightAnchor constant:16].active = YES;
    [_titleField.topAnchor constraintEqualToAnchor:self.imageView.topAnchor].active = YES;
    [_titleField.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-49].active = YES;
    
    
    //内容
    self.contentField = [[NSTextField alloc]init];
    _contentField.editable = NO;
    _contentField.bordered = NO;
    _contentField.selectable  = NO;
    _contentField.backgroundColor = NSColor.whiteColor;
    _contentField.font = [NSFont systemFontOfSize:14];
    _contentField.textColor = [NSColor colorWithRed:92/255. green:98/255. blue:107/255. alpha:1];
    _contentField.maximumNumberOfLines = 0;
    
    [self addSubview:_contentField];
    _contentField.translatesAutoresizingMaskIntoConstraints = NO;
    [_contentField.leftAnchor constraintEqualToAnchor:_titleField.leftAnchor].active = YES;
    [_contentField.topAnchor constraintEqualToAnchor:_titleField.bottomAnchor constant:9].active = YES;
    [_contentField.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-29].active = YES;
    
    
    NSButton *lastBtn = [NSButton buttonWithTitle:_buttonTitles[_buttonTitles.count-1] target:self action:@selector(buttonAction:)];
    lastBtn.tag = _buttonTitles.count - 1;
    [self setWithButton:lastBtn defaultStyle:_defaultIdx == _buttonTitles.count - 1];
    
    [self addSubview:lastBtn];
    lastBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [lastBtn.topAnchor constraintEqualToAnchor:_contentField.bottomAnchor constant:24].active = YES;
    [lastBtn.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-20].active = YES;
    [lastBtn.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-13].active = YES;
    [lastBtn.widthAnchor constraintEqualToConstant:64].active = YES;
    [lastBtn.heightAnchor constraintEqualToConstant:32].active = YES;
    
    
    NSButton *rightBtn = lastBtn;
    for (NSInteger i = _buttonTitles.count - 2; i >= 0; i--) {
        
        NSButton *btn = [NSButton buttonWithTitle:_buttonTitles[i] target:self action:@selector(buttonAction:)];
        btn.tag = i;
        [self setWithButton:btn defaultStyle:_defaultIdx == i];
        [self addSubview:btn];
        btn.translatesAutoresizingMaskIntoConstraints = NO;
        [btn.rightAnchor constraintEqualToAnchor:rightBtn.leftAnchor constant:-12].active = YES;
        [btn.centerYAnchor constraintEqualToAnchor:rightBtn.centerYAnchor].active = YES;
        [btn.widthAnchor constraintEqualToConstant:64].active = YES;
        [btn.heightAnchor constraintEqualToConstant:32].active = YES;
        
        rightBtn = btn;
    }
    
}

- (void)setWithButton:(NSButton*)btn defaultStyle:(BOOL)defaultStyle {
    
    if(defaultStyle){
        
        btn.bordered = NO;
        btn.wantsLayer = YES;
        btn.layer.backgroundColor = [NSColor colorWithRed:0 green:120/255. blue:250/255. alpha:1].CGColor;
        btn.layer.cornerRadius = 4;
        [self setButtonTextColor:btn textColor:NSColor.whiteColor];
        
    }else{
        
        btn.wantsLayer = YES;
        btn.layer.cornerRadius = 4;

        //自带边缘false
        btn.bordered = NO;
        btn.bezelStyle = NSBezelStyleTexturedSquare;

        btn.layer.backgroundColor = NSColor.whiteColor.CGColor;
        btn.layer.borderColor = [NSColor colorWithRed:203/255. green:207/255. blue:214/255. alpha:1].CGColor;
        btn.layer.borderWidth = 1;
        
        [self setButtonTextColor:btn textColor:[NSColor colorWithRed:32/255. green:42/255. blue:48/255. alpha:1]];
    }
}

- (void)buttonAction:(NSButton*)btn {
    
    [self close];
    
    if (_onAction) {
        _onAction(btn.tag,_buttonTitles[btn.tag]);
    }
}

- (void)setUI2 {
    
    
    //左侧图标
    self.imageView = [[NSImageView alloc]init];
    [self addSubview:self.imageView];
    _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    [_imageView.leftAnchor constraintEqualToAnchor:self.leftAnchor constant:30].active = YES;
    [_imageView.topAnchor constraintEqualToAnchor:self.topAnchor constant:48].active = YES;
    [_imageView.widthAnchor constraintEqualToConstant:24].active = YES;
    [_imageView.heightAnchor constraintEqualToConstant:24].active = YES;
    

    //标题
    self.titleField = [[NSTextField alloc]init];
    _titleField.editable = NO;
    _titleField.bordered = NO;
    _titleField.selectable  = NO;
    _titleField.backgroundColor = NSColor.whiteColor;
    _titleField.font = [NSFont systemFontOfSize:16];
    _titleField.textColor = [NSColor colorWithRed:38/255. green:42/255. blue:48/255. alpha:1];
    _titleField.maximumNumberOfLines = 0;

    [self addSubview:_titleField];
    _titleField.translatesAutoresizingMaskIntoConstraints = NO;
    [_titleField.leftAnchor constraintEqualToAnchor:self.imageView.rightAnchor constant:16].active = YES;
    [_titleField.topAnchor constraintEqualToAnchor:self.imageView.topAnchor].active = YES;
    [_titleField.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-49].active = YES;
    
    
    //内容
    self.contentField = [[NSTextField alloc]init];
    _contentField.editable = NO;
    _contentField.bordered = NO;
    _contentField.selectable  = NO;
    _contentField.backgroundColor = NSColor.whiteColor;
    _contentField.font = [NSFont systemFontOfSize:14];
    _contentField.textColor = [NSColor colorWithRed:92/255. green:98/255. blue:107/255. alpha:1];
    _contentField.maximumNumberOfLines = 0;
    
    [self addSubview:_contentField];
    _contentField.translatesAutoresizingMaskIntoConstraints = NO;
    [_contentField.leftAnchor constraintEqualToAnchor:_titleField.leftAnchor].active = YES;
    [_contentField.topAnchor constraintEqualToAnchor:_titleField.bottomAnchor constant:9].active = YES;
    [_contentField.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-29].active = YES;
    
    //确定按钮
    self.sureBtn = [NSButton buttonWithTitle:@"确定" target:self action:@selector(sureAction)];
    _sureBtn.bordered = NO;
    _sureBtn.wantsLayer = YES;
    _sureBtn.layer.backgroundColor = [NSColor colorWithRed:0 green:120/255. blue:250/255. alpha:1].CGColor;
    _sureBtn.layer.cornerRadius = 4;
    [self setButtonTextColor:_sureBtn textColor:NSColor.whiteColor];
    
    [self addSubview:_sureBtn];
    _sureBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [_sureBtn.topAnchor constraintEqualToAnchor:_contentField.bottomAnchor constant:24].active = YES;
    [_sureBtn.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-20].active = YES;
    [_sureBtn.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-13].active = YES;
    [_sureBtn.widthAnchor constraintEqualToConstant:64].active = YES;
    [_sureBtn.heightAnchor constraintEqualToConstant:32].active = YES;
    
    //取消按钮
    self.cancelBtn = [NSButton buttonWithTitle:@"取消" target:self action:@selector(cancelAction)];
    
    _cancelBtn.wantsLayer = YES;
    _cancelBtn.layer.cornerRadius = 4;
    
    //自带边缘false
    _cancelBtn.bordered = NO;
    _cancelBtn.bezelStyle = NSBezelStyleTexturedSquare;

    _cancelBtn.layer.backgroundColor = NSColor.whiteColor.CGColor;
    _cancelBtn.layer.borderColor = [NSColor colorWithRed:203/255. green:207/255. blue:214/255. alpha:1].CGColor;
    _cancelBtn.layer.borderWidth = 1;
    
    [self setButtonTextColor:_cancelBtn textColor:[NSColor colorWithRed:32/255. green:42/255. blue:48/255. alpha:1]];
    
    [self addSubview:_cancelBtn];
    _cancelBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [_cancelBtn.rightAnchor constraintEqualToAnchor:_sureBtn.leftAnchor constant:-12].active = YES;
    [_cancelBtn.centerYAnchor constraintEqualToAnchor:_sureBtn.centerYAnchor].active = YES;
    [_cancelBtn.widthAnchor constraintEqualToConstant:64].active = YES;
    [_cancelBtn.heightAnchor constraintEqualToConstant:32].active = YES;
    
}

- (void)setButtonTextColor:(NSButton*)btn textColor:(NSColor*)textColor {
    
    NSMutableAttributedString *attrTitle =
    
    [[NSMutableAttributedString alloc] initWithAttributedString:[btn attributedTitle]];
    
    NSUInteger len = [attrTitle length];
    
    NSRange range = NSMakeRange(0, len);
    
    [attrTitle addAttribute:NSForegroundColorAttributeName value:textColor range:range];
    
    [attrTitle fixAttributesInRange:range];
    
    [btn setAttributedTitle:attrTitle];
}

- (void)close {
    if (_windowTransparentckView) {
        [_windowTransparentckView removeFromSuperview];
    }
    
    [self removeFromSuperview];
}

- (void)sureAction {
    
    [self close];
    
    if(_sure){
        _sure();
    }
}

- (void)cancelAction {
    
    [self close];
    
    if(_cancel){
        _cancel();
    }
}


/// 显示alertview
/// @param title title description
/// @param content content description
/// @param type type 1: 信息  2:警告  左侧图标区分
/// @param cancel 取消
/// @param sure 确认
+ (void)showWithTitle:(NSString*)title
              content:(NSString*)content
                 type:(NSInteger)type
               cancel:(void(^)(void))cancel
                 sure:(void(^)(void))sure
{
    
    if (![NSThread isMainThread]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self showWithTitle:title content:content type:type cancel:cancel sure:sure];
        });
        
        return;
    }
    
    NSWindow *keywindow = [NSApplication sharedApplication].keyWindow;
    NSView *superView = keywindow.contentView.superview;

    if ( ![superView isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")] ){
        
        keywindow = [NSApplication sharedApplication].mainWindow;
        superView = keywindow.contentView.superview;
    }
    
    NSView *windowBackView = [[NSCustomTransparentView alloc]init];
    windowBackView.wantsLayer = YES;
    windowBackView.layer.backgroundColor = [NSColor colorWithRed:0 green:0 blue:0 alpha:0.4].CGColor;
    windowBackView.frame = superView.frame;
    [superView addSubview:windowBackView];
    windowBackView.translatesAutoresizingMaskIntoConstraints = NO;
    [windowBackView.centerYAnchor constraintEqualToAnchor:superView.centerYAnchor].active = YES;
    [windowBackView.centerXAnchor constraintEqualToAnchor:superView.centerXAnchor].active = YES;
    [windowBackView.widthAnchor constraintEqualToAnchor:superView.widthAnchor].active = YES;
    [windowBackView.heightAnchor constraintEqualToAnchor:superView.heightAnchor].active = YES;

    
    NSCustomAlertView *alertView = [[NSCustomAlertView alloc]init];

    alertView.cancel = cancel;
    alertView.sure = sure;
    
    [alertView setUI2];
    
    alertView.titleField.stringValue = title;
    alertView.contentField.stringValue = content;
    
  
    NSMutableParagraphStyle *textParagraph = [[NSMutableParagraphStyle alloc] init];
    [textParagraph setLineSpacing:8.0];
    NSDictionary *attrDic = [NSDictionary dictionaryWithObjectsAndKeys: textParagraph, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:title attributes:attrDic];
    [alertView.titleField setAllowsEditingTextAttributes:YES];
    [alertView.titleField setAttributedStringValue:attrString];
    
    NSDictionary *attrDic1 = [NSDictionary dictionaryWithObjectsAndKeys: textParagraph, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString1 = [[NSAttributedString alloc] initWithString:content attributes:attrDic1];
    [alertView.contentField setAllowsEditingTextAttributes:YES];
    [alertView.contentField setAttributedStringValue:attrString1];
    
   
    alertView.imageView.image = [NSImage imageNamed: type == 1 || type == 3 ? @"icon_info" : @"icon_warning"];
    
    
    alertView.windowTransparentckView = windowBackView;

  

    alertView.wantsLayer = YES;
    alertView.layer.backgroundColor = NSColor.whiteColor.CGColor;
    alertView.layer.cornerRadius = 3;
    
    [superView addSubview:alertView];
    alertView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [alertView.centerXAnchor constraintEqualToAnchor:superView.centerXAnchor].active = YES;
    [alertView.centerYAnchor constraintEqualToAnchor:superView.centerYAnchor].active = YES;
    [alertView.widthAnchor constraintEqualToConstant:420].active = YES;
//    [alertView.heightAnchor constraintGreaterThanOrEqualToConstant:174].active = YES;
    
    if (type == 3) {
        alertView.cancelBtn.hidden = YES;
    }
    
   
}


/// 显示alertview
/// @param title title description
/// @param content content description
/// @param type type 1: 信息  2:警告  左侧图标区分
/// @param buttonTitles buttonTitles 按钮标题
/// @param defaultIdx  蓝色按钮在buttonTitles的索引(第一位为0)
/// @param action action description
+ (void)showWithTitle:(NSString*)title
              content:(NSString*)content
                 type:(NSInteger)type
               buttons:(NSArray<NSString*>*)buttonTitles
           defaultIdx:(NSInteger)defaultIdx
                 action:(void(^)(NSInteger idx, NSString *title))action
{
    
    if (![NSThread isMainThread]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self showWithTitle:title content:content type:type buttons:buttonTitles defaultIdx:defaultIdx action:action];
        });
        
        return;
    }
    
    NSWindow *keywindow = [NSApplication sharedApplication].keyWindow;
    NSView *superView = keywindow.contentView.superview;

    if ( ![superView isKindOfClass:NSClassFromString(@"NSTitlebarContainerView")] ){
        
        keywindow = [NSApplication sharedApplication].mainWindow;
        superView = keywindow.contentView.superview;
    }
    
    NSView *windowBackView = [[NSCustomTransparentView alloc]init];
    windowBackView.wantsLayer = YES;
    windowBackView.layer.backgroundColor = [NSColor colorWithRed:0 green:0 blue:0 alpha:0.4].CGColor;
    windowBackView.frame = superView.frame;
    [superView addSubview:windowBackView];
    windowBackView.translatesAutoresizingMaskIntoConstraints = NO;
    [windowBackView.centerYAnchor constraintEqualToAnchor:superView.centerYAnchor].active = YES;
    [windowBackView.centerXAnchor constraintEqualToAnchor:superView.centerXAnchor].active = YES;
    [windowBackView.widthAnchor constraintEqualToAnchor:superView.widthAnchor].active = YES;
    [windowBackView.heightAnchor constraintEqualToAnchor:superView.heightAnchor].active = YES;

    
    NSCustomAlertView *alertView = [[NSCustomAlertView alloc]init];

    alertView.buttonTitles = buttonTitles;
    alertView.onAction = action;
    alertView.defaultIdx = defaultIdx;
    [alertView setUI];
    alertView.titleField.stringValue = title;
    alertView.contentField.stringValue = content;
    
  
    NSMutableParagraphStyle *textParagraph = [[NSMutableParagraphStyle alloc] init];
    [textParagraph setLineSpacing:8.0];
    NSDictionary *attrDic = [NSDictionary dictionaryWithObjectsAndKeys: textParagraph, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:title attributes:attrDic];
    [alertView.titleField setAllowsEditingTextAttributes:YES];
    [alertView.titleField setAttributedStringValue:attrString];
    
    NSDictionary *attrDic1 = [NSDictionary dictionaryWithObjectsAndKeys: textParagraph, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString1 = [[NSAttributedString alloc] initWithString:content attributes:attrDic1];
    [alertView.contentField setAllowsEditingTextAttributes:YES];
    [alertView.contentField setAttributedStringValue:attrString1];
    
   
    alertView.imageView.image = [NSImage imageNamed: type == 1 || type == 3 ? @"icon_info" : @"icon_warning"];
    
    alertView.windowTransparentckView = windowBackView;

    alertView.wantsLayer = YES;
    alertView.layer.backgroundColor = NSColor.whiteColor.CGColor;
    alertView.layer.cornerRadius = 3;
    
    [superView addSubview:alertView];
    alertView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [alertView.centerXAnchor constraintEqualToAnchor:superView.centerXAnchor].active = YES;
    [alertView.centerYAnchor constraintEqualToAnchor:superView.centerYAnchor].active = YES;
    [alertView.widthAnchor constraintEqualToConstant:420].active = YES;

    
   
}


@end
